﻿using System;
using System.Threading;

namespace SemaphoreDemo
{
    /*
        https://leetcode.cn/problems/print-in-order/

       C#：多线程--信号量（Semaphore）
     */
    public class Foo
    {

        public Foo()
        {

        }
        System.Threading.Semaphore sema1 = new System.Threading.Semaphore(0, 1);
        System.Threading.Semaphore sema2 = new System.Threading.Semaphore(0, 1);

        public void First(Action printFirst)
        {
            printFirst();
            sema1.Release();
        }

        public void Second(Action printSecond)
        {
            sema1.WaitOne();
            printSecond();
            sema2.Release();
        }

        public void Third(Action printThird)
        {
            sema2.WaitOne();
            printThird();
        }
    }
    class Program
    {
        static Foo foo = new Foo();

        static void Main(string[] args)
        {

            Thread thread = new Thread(new ParameterizedThreadStart(Run1));
            thread.Start(thread.Name);

            Thread thread3 = new Thread(new ParameterizedThreadStart(Run3));
            thread3.Name = $"编号";
            thread3.Start(thread3.Name);

            Thread thread2 = new Thread(new ParameterizedThreadStart(Run2));
            thread2.Name = $"编号";
            thread2.Start(thread2.Name);
        }

        static void Run1(object obj)
        {
            foo.First(() =>
            {
                Console.WriteLine("First");
            });
        }
        static void Run2(object obj)
        {
            foo.Second(() =>
            {
                Console.WriteLine("Second");
            });
        }
        static void Run3(object obj)
        {
            foo.Third(() =>
            {
                Console.WriteLine("Third");
            });
        }

    }
}
